package message;

import java.util.List;

import org.hashids.Hashids;

import com.demo.common.model.FdRoomUser;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zhenyi.common.model.TgUser;
import com.zhenyi.tuangou.index.TGController;

public class MessageController extends TGController {
	protected final Hashids hashids = new Hashids("zhenyi", 6);
	protected final int PAGE_SIZE = 50;
	
	/**
	 * 加入聊天室
	 */
	public void joinRoom() {
		Long roomId = getParaToLong("id");
		int pageNumber = getParaToInt("pageNumber",1);//默认第一页
		if (roomId == null) {
			renderError(404);
			return;
		}
		TgUser user = getUser();

		Kv cond1 = Kv.by("roomId", roomId);
		SqlPara sqlPara1 = Db.use("demo").getSqlPara("findMessage", cond1);
		Page<Record> list = Db.use("demo").paginate(pageNumber, PAGE_SIZE, sqlPara1);
		for (Record record : list.getList()) {
			TgUser fromUser = TgUser.dao.findById(record.getLong("fromUserId"));
			record.set("fromUserName", fromUser.getName());
			record.set("fromUserLogo", fromUser.getLogo());
			record.set("fromUserId", user.getId());
		}

		Kv cond = Kv.by("roomId", roomId);
		cond.set("userId", user.getId());
		SqlPara sqlPara = Db.use("demo").getSqlPara("findUserInRoom", cond);
		Record record = Db.use("demo").findFirst(sqlPara);
		if (record == null) {
			FdRoomUser fdRoomUser = new FdRoomUser();
			fdRoomUser.setRoomId(roomId);
			fdRoomUser.setUserCode(user.getUid());
			fdRoomUser.setUserId(user.getId());
			fdRoomUser.save();
			record = Db.use("demo").findFirst(sqlPara);
		}
		setAttr("list", list);//聊天记录
		setAttr("record", record);
		render("/res/socket2.html");
		// renderJson(record);
	}

	/**
	 * 退出群聊
	 */
	public void quitRoom() {
		Long userId = getParaToLong("userId");
		Long roomId = getParaToLong("roomId");
		Kv cond = Kv.by("roomId", roomId);
		cond.set("userId", userId);
		SqlPara sqlPara = Db.use("demo").getSqlPara("findUserInRoom", cond);
		Record record = Db.use("demo").findFirst(sqlPara);
		if (record != null) {
			FdRoomUser.dao.deleteById(record.getLong("id"));
		}
		renderJson("ok");
	}

	/**
	 * 我的聊天室
	 */
	@Clear
	public void roomList() {
		TgUser tgUser = getUser();
		Kv cond = Kv.by("userId", tgUser.getId());
		SqlPara sqlPara = Db.use("demo").getSqlPara("findRoomList", cond);
		List<Record> list = Db.use("demo").find(sqlPara);
		for (Record record : list) {
			Kv cond1 = Kv.by("roomId", record.getLong("id"));
			SqlPara sqlPara2 = Db.use("demo").getSqlPara("findRoomMessageFirst", cond1);
			Record record2 = Db.use("demo").findFirst(sqlPara2);
			if (record2 == null) {
				record.set("content", "");
			} else {
				record.set("content", record2.getStr("content"));
			}
		}
		renderJson(list);
	}
}
